﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.WebControls;

namespace Runda.CMS.Portal.ContractFollowUp
{
    public partial class InstrumentMaintainHistory : BasePage
    {
        public Guid MaintainID
        {
            get
            {
                if (hiddenRegisterID.Value == string.Empty) return Guid.Empty;
                else return new Guid(hiddenRegisterID.Value);
            }
            set
            {
                hiddenRegisterID.Value = value.ToString();
            }
        }

        public Guid AssemblyID
        {
            get
            {
                if (hiddenAssemblyID.Value == string.Empty) return Guid.Empty;
                else return new Guid(hiddenAssemblyID.Value);
            }
            set
            {
                hiddenAssemblyID.Value = value.ToString();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                

                GuaranteeInfo.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.GuaranteeType)));
                ServiceContract.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.ContractServiceType)));
                InstrumentStatus.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.InstrumentStatus)));

                if (Request.QueryString["MaintainID"] != null)
                {
                    MaintainID = new Guid(Request.QueryString["MaintainID"]);
                    WsmMaintainBillEntity entity = new SystemBll().Get<WsmMaintainBillEntity>(MaintainID);

                    if (!base.CheckUserHasFuction(1, "Func5093"))
                    {
                        lnkbtnSave.Visible = false;
                    }
                    else
                    {
                        if (entity.AccessoryCheckStatus >= (int)Enumerator.AccessoryReplacementCheckStatus.Submit)
                        {
                            lnkbtnSave.Enabled = false;

                            setData1LockStatus(false);
                            setData2LockStatus(false);
                            setData3LockStatus(false);

                            if (base.CheckUserHasFuction(1, "Func5111"))
                            { setData1LockStatus(true); }
                            if (base.CheckUserHasFuction(1, "Func5112"))
                            { setData2LockStatus(true); }
                            if (base.CheckUserHasFuction(1, "Func5113"))
                            { setData3LockStatus(true); }

                            if (base.CheckUserHasFuction(1, "Func5111") || base.CheckUserHasFuction(1, "Func5112") || base.CheckUserHasFuction(1, "Func5113"))
                            { lnkbtnSave.Visible = true; }
                        }
                    }


                    WsmTaskRegisterEntity taskEntity = new SystemBll().Get<WsmTaskRegisterEntity>(entity.RegisterID);

                    hidCustomerGUID.Value = taskEntity.CustomerID.ToString();

                    CtrtCustomerEntity customerEntity = new SystemBll().Get<CtrtCustomerEntity>(taskEntity.CustomerID);
                    txtCustomerAddr.Text = customerEntity.CustomerAddress;
                    //客户区域
                    WsmCustomerExtensionEntity CusExtEntity = new SystemBll().Get<WsmCustomerExtensionEntity>(taskEntity.CustomerID);
                    if (CusExtEntity != null)
                    {
                        ddlCustomerArea.SelectedValue = CusExtEntity.CustomerArea;
                    }

                    ManufacInstrumentCode.Text = new SystemBll().Get<WsmInstrumentInfoEntity>(taskEntity.InstrumentID).instrumentCode;
                    List<WsmInstrumentAssemblyEntity> assemblylist = new SystemBll().GetAll<WsmInstrumentAssemblyEntity>(" and MaintainID='" + MaintainID.ToString() + "'");
                    if (assemblylist != null && assemblylist.Count > 0)
                    {
                        WsmInstrumentAssemblyEntity assemblyEntity = assemblylist[0];

                        if (assemblyEntity.SerialNum != null && assemblyEntity.SerialNum.ToString() != "")
                        {
                            SerialNum.Enabled = false;
                        }

                        AssemblyID = assemblyEntity.AssemblyID;
                        InstallDate.SelectedDate = assemblyEntity.InstallDate;
                        GuaranteeInfo.SelectedValue = assemblyEntity.GuaranteeInfo;
                        WarrantyFrom.SelectedDate = assemblyEntity.WarrantyFrom;
                        WarrantyTo.SelectedDate = assemblyEntity.WarrantyTo;
                        GuaranteeFrequency.Value = System.Convert.ToDouble(assemblyEntity.GuaranteeFrequency);
                        ManufacInstrumentCode.Text = assemblyEntity.ManufacInstrumentCode;
                        ServiceContract.SelectedValue = assemblyEntity.ServiceContract;
                        CompanyInstrumentCode.Text = assemblyEntity.CompanyInstrumentCode;
                        ReturnVisitFrequency.Value = System.Convert.ToDouble(assemblyEntity.ReturnVisitFrequency);
                        SoftWareVersion.Text = assemblyEntity.SoftWareVersion;
                        HasTrainCertificate.SelectedValue = assemblyEntity.HasTrainCertificate.ToString();
                        CalibrationFrequency.Value = System.Convert.ToDouble(assemblyEntity.CalibrationFrequency);
                        SerialNum.Text = assemblyEntity.SerialNum;
                        InstrumentBeginUse.SelectedDate = assemblyEntity.InstrumentBeginUse;
                        InstrumentBelongto.Text = assemblyEntity.InstrumentBelongto;
                        InstrumentMode.Text = assemblyEntity.InstrumentMode;
                        InstrumentApplicateSituation.Text = assemblyEntity.InstrumentApplicateSituation;
                        InstrumentStatus.SelectedValue = assemblyEntity.InstrumentStatus;
                        HasReadNum.SelectedValue = assemblyEntity.HasReadNum.ToString();
                        DayEstimate.Value = System.Convert.ToDouble(assemblyEntity.DayEstimate);
                        ReadNumType.SelectedValue = assemblyEntity.ReadNumType.ToString();
                        GuaranteebeginDate.SelectedDate = assemblyEntity.GuaranteebeginDate;
                        ReturnVisitbeginDate.SelectedDate = assemblyEntity.ReturnVisitbeginDate;
                        CalibrationbeginDate.SelectedDate = assemblyEntity.CalibrationbeginDate;
                        ConservationManGUID.Value = assemblyEntity.ConservationMan.ToString();
                        txtdy1.Text = assemblyEntity.dy1;
                        txtdy2.Text = assemblyEntity.dy2;
                        txtInstrumentWhere.Text = assemblyEntity.InstrumentWhere;
                        txtWhereTel.Text = assemblyEntity.WhereTel;
                        txtSales.Text = assemblyEntity.Sales;
                        txtAgencyName.Text = assemblyEntity.AgencyName;
                        txtAgencyMan.Text = assemblyEntity.AgencyMan;
                        txtAgencyTel.Text = assemblyEntity.AgencyTel;
                        txtMemo.Text = assemblyEntity.Memo;

                        if (assemblyEntity.HasAgency != null)
                        { ddlHasAgency.SelectedValue = assemblyEntity.HasAgency; }

                        ConservationManName.Text = new SystemBll().Get<SysUserEntity>(new Guid(ConservationManGUID.Value)).UserName;

                        AdjustManGUID.Value = assemblyEntity.AdjustMan.ToString();
                        AdjustManName.Text = new SystemBll().Get<SysUserEntity>(new Guid(AdjustManGUID.Value)).UserName;

                        returnVisitManGUID.Value = assemblyEntity.ReturnVisitMan.ToString();
                        returnVisitManName.Text = new SystemBll().Get<SysUserEntity>(new Guid(returnVisitManGUID.Value)).UserName;

                        ReadNumManageManGUID.Value = assemblyEntity.ReadNumManageMan.ToString();
                        if (assemblyEntity.ReadNumManageMan != System.Guid.Empty)
                        {
                            ReadNumManageManName.Text = new SystemBll().Get<SysUserEntity>(new Guid(ReadNumManageManGUID.Value)).UserName;
                        }
                        ReadNumBeginDate.SelectedDate = assemblyEntity.ReadNumBeginDate;
                        ReadNumFrequency.Value = System.Convert.ToDouble(assemblyEntity.ReadNumFrequency);
                    }
                }
                BindList(1);
                BindList2(1);
            }
        }
        private void BindList(int pageindex) {
            if (Request.QueryString["MaintainID"] != null)
            {
                MaintainID = new Guid(Request.QueryString["MaintainID"]);
                WsmMaintainBillEntity entity = new SystemBll().Get<WsmMaintainBillEntity>(MaintainID);
                WsmTaskRegisterEntity taskEntity = new SystemBll().Get<WsmTaskRegisterEntity>(entity.RegisterID);
                List<WsmMaintainBillEntity> list = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID in ( select RegisterID from Cms_Wsm_TaskRegister where (TaskType=" + System.Convert.ToInt32(Enumerator.SalesService.RepairFE) + " or TaskType=" + System.Convert.ToInt32(Enumerator.SalesService.RepairLS) + ") and TaskStatus = 1 and InstrumentSerialNum='" + taskEntity.InstrumentSerialNum + "')");
                RepeaterUsers.DataSource = list;
                RepeaterUsers.DataBind();
            }
        }
        private void BindList2(int pageindex)
        {
            if (Request.QueryString["MaintainID"] != null)
            {
                MaintainID = new Guid(Request.QueryString["MaintainID"]);
                WsmMaintainBillEntity entity = new SystemBll().Get<WsmMaintainBillEntity>(MaintainID);
                WsmTaskRegisterEntity taskEntity = new SystemBll().Get<WsmTaskRegisterEntity>(entity.RegisterID);
                List<WsmMaintainBillEntity> list = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID in ( select RegisterID from Cms_Wsm_TaskRegister where (TaskType=" + System.Convert.ToInt32(Enumerator.SalesService.RepairFE) + " or TaskType=" + System.Convert.ToInt32(Enumerator.SalesService.RepairLS) + ") and TaskStatus = 1 and InstrumentID='" + taskEntity.InstrumentID.ToString() + "')");
                Repeater1.DataSource = list;
                Repeater1.DataBind();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindList(AspNetPager1.CurrentPageIndex);
        }
        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            BindList2(AspNetPager2.CurrentPageIndex);
        }
        protected void RepeaterUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label Maintainer = e.Item.FindControl("Maintainer") as Label;
            Label MaintainerName = e.Item.FindControl("MaintainerName") as Label;
            if (Maintainer != null)
            {
                MaintainerName.Text = new SystemBll().Get<SysUserEntity>(new Guid(Maintainer.Text)).UserName;
            }
        }
        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label Maintainer = e.Item.FindControl("Maintainer") as Label;
            Label MaintainerName = e.Item.FindControl("MaintainerName") as Label;
            Label MaintainID = e.Item.FindControl("MaintainID") as Label;
            Label CustomerName = e.Item.FindControl("CustomerName") as Label;        
            if (Maintainer != null)
            {
                MaintainerName.Text = new SystemBll().Get<SysUserEntity>(new Guid(Maintainer.Text)).UserName;
                CustomerName.Text = new SystemBll().GetAll<CtrtCustomerEntity>(" and CustomerID in( select CustomerID from Cms_Wsm_TaskRegister where  RegisterID in ( select RegisterID from Cms_Wsm_MaintainBill where MaintainID='" + MaintainID.Text.ToString() + "'))")[0].CustomerName;
            }
        }

        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveerror", "alert('" + Message + "');", true);
            }
            else
                ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功')", true);
        }

        private void setData1LockStatus(Boolean lockStatus)
        {
            InstallDate.Enabled = lockStatus;
            InstrumentBeginUse.Enabled = lockStatus;
            SoftWareVersion.Enabled = lockStatus;
            txtdy1.Enabled = lockStatus;
            txtdy2.Enabled = lockStatus;
            HasReadNum.Enabled = lockStatus;
            ReadNumType.Enabled = lockStatus;
            txtCustomerAddr.Enabled = lockStatus;
            ddlCustomerArea.Enabled = lockStatus;
            txtInstrumentWhere.Enabled = lockStatus;
            txtWhereTel.Enabled = lockStatus;
        }

        private void setData2LockStatus(Boolean lockStatus)
        {
            GuaranteeFrequency.Enabled = lockStatus;
            GuaranteebeginDate.Enabled = lockStatus;
            ReturnVisitFrequency.Enabled = lockStatus;
            ReturnVisitbeginDate.Enabled = lockStatus;
            CalibrationFrequency.Enabled = lockStatus;
            CalibrationbeginDate.Enabled = lockStatus;
            ReadNumFrequency.Enabled = lockStatus;
            ReadNumBeginDate.Enabled = lockStatus;
        }

        private void setData3LockStatus(Boolean lockStatus)
        {
            GuaranteeInfo.Enabled = lockStatus;
            WarrantyFrom.Enabled = lockStatus;
            WarrantyTo.Enabled = lockStatus;
            DayEstimate.Enabled = lockStatus;
            HasTrainCertificate.Enabled = lockStatus;
            txtSales.Enabled = lockStatus;
            ddlHasAgency.Enabled = lockStatus;
            txtAgencyName.Enabled = lockStatus;
            txtAgencyMan.Enabled = lockStatus;
            txtAgencyTel.Enabled = lockStatus;
        }

        private bool save(ref string message)
        {
            bool isSuccess = true;

            try
            {
                WsmInstrumentAssemblyEntity entity = new WsmInstrumentAssemblyEntity();

                SystemBll bll = new SystemBll();
                if (AssemblyID != Guid.Empty)
                {
                    entity = bll.Get<WsmInstrumentAssemblyEntity>(AssemblyID);
                }
                else
                {
                    message = "装机信息加载有误，无法继续保存";
                    isSuccess = false;
                }

                if (InstallDate.SelectedDate != null)
                    entity.InstallDate = InstallDate.SelectedDate.Value;
                entity.GuaranteeInfo = GuaranteeInfo.SelectedValue.Trim();
                if (WarrantyFrom.SelectedDate != null)
                    entity.WarrantyFrom = WarrantyFrom.SelectedDate.Value;
                if (WarrantyTo.SelectedDate != null)
                    entity.WarrantyTo = WarrantyTo.SelectedDate.Value;
                entity.GuaranteeFrequency = System.Convert.ToInt32(GuaranteeFrequency.Value);
                entity.ManufacInstrumentCode = ManufacInstrumentCode.Text.Trim();
                entity.ServiceContract = ServiceContract.SelectedValue;
                entity.CompanyInstrumentCode = CompanyInstrumentCode.Text.Trim();
                entity.ReturnVisitFrequency = System.Convert.ToInt32(ReturnVisitFrequency.Value);
                entity.SoftWareVersion = SoftWareVersion.Text.Trim();
                entity.HasTrainCertificate = System.Convert.ToInt32(HasTrainCertificate.SelectedValue);
                entity.CalibrationFrequency = System.Convert.ToInt32(CalibrationFrequency.Value);
                entity.SerialNum = SerialNum.Text.Trim();
                if (InstrumentBeginUse.SelectedDate != null)
                    entity.InstrumentBeginUse = InstrumentBeginUse.SelectedDate.Value;
                entity.InstrumentBelongto = InstrumentBelongto.Text.Trim();
                entity.InstrumentMode = InstrumentMode.Text.Trim();
                entity.InstrumentApplicateSituation = InstrumentApplicateSituation.Text;
                entity.InstrumentStatus = InstrumentStatus.SelectedValue;
                entity.HasReadNum = System.Convert.ToInt32(HasReadNum.SelectedValue);
                entity.DayEstimate = System.Convert.ToDecimal(DayEstimate.Value);
                entity.ReadNumType = System.Convert.ToInt32(ReadNumType.SelectedValue);
                if (GuaranteebeginDate.SelectedDate != null)
                    entity.GuaranteebeginDate = GuaranteebeginDate.SelectedDate.Value;
                if (ReturnVisitbeginDate.SelectedDate != null)
                    entity.ReturnVisitbeginDate = ReturnVisitbeginDate.SelectedDate.Value;
                entity.ConservationMan = new Guid(ConservationManGUID.Value);
                entity.AdjustMan = new Guid(AdjustManGUID.Value);
                entity.ReturnVisitMan = new Guid(returnVisitManGUID.Value);
                entity.dy1 = txtdy1.Text;
                entity.dy2 = txtdy2.Text;
                entity.InstrumentWhere = txtInstrumentWhere.Text;
                entity.WhereTel = txtWhereTel.Text;
                entity.Sales = txtSales.Text;
                entity.AgencyName = txtAgencyName.Text;
                entity.AgencyMan = txtAgencyMan.Text;
                entity.AgencyTel = txtAgencyTel.Text;
                entity.Memo = txtMemo.Text;

                if (ddlHasAgency.SelectedValue != "9")
                {
                    entity.HasAgency = ddlHasAgency.SelectedValue.ToString();
                }
                else
                { entity.HasAgency = null; }
                if (CalibrationbeginDate.SelectedDate != null)
                    entity.CalibrationbeginDate = CalibrationbeginDate.SelectedDate.Value;
                if (ReadNumManageManGUID.Value != "")
                {
                    entity.ReadNumManageMan = new Guid(ReadNumManageManGUID.Value);
                }

                if (ReadNumBeginDate.SelectedDate != null)
                {
                    entity.ReadNumBeginDate = ReadNumBeginDate.SelectedDate.Value;
                }
                entity.ReadNumFrequency = System.Convert.ToInt32(ReadNumFrequency.Value);

                bll.InsertOrUpdate(entity);
                //更新客户地址
                CtrtCustomerEntity customerEntity = new SystemBll().Get<CtrtCustomerEntity>(new Guid(hidCustomerGUID.Value));
                customerEntity.CustomerAddress = txtCustomerAddr.Text;
                bll.InsertOrUpdate(customerEntity);
                WsmCustomerExtensionEntity customerEntityex = new SystemBll().Get<WsmCustomerExtensionEntity>(new Guid(hidCustomerGUID.Value));
                customerEntityex.CustomerArea = ddlCustomerArea.SelectedValue;
                bll.InsertOrUpdate(customerEntityex);

                
                List<WsmInstrumentRecordEntity> recordList = bll.GetAll<WsmInstrumentRecordEntity>(" and MaintainID='" + MaintainID.ToString() + "'");
                foreach (WsmInstrumentRecordEntity recordEntity in recordList)
                {
                    recordEntity.SerialNum = SerialNum.Text.Trim();
                    bll.Update(recordEntity);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                isSuccess = false;
            }

           
            return isSuccess;
        }
    }
}
